<template>
    <div class="app-container">
        <div>
            <p class="dialogTitle title">当前地震事件:
                <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
                <span v-else>请在地震事件管理中设置当前地震事件</span>
            </p>
        </div>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent||dataList.length==1" @click="handleCreat">生成灾评报告</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe>
            <el-table-column label="序号" align="center" type="index" width="55" />
            <el-table-column label="灾评报告编号" align="center" prop="number">
                <template #default="scope">
                    <el-button type="text" @click="handleCoverReport(scope.row)">{{ scope.row.number }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="灾评报告名称" align="center" prop="name" />
            <el-table-column label="创建单位" align="center" prop="unit" />
            <el-table-column label="创建人" align="center" prop="createUser" />
            <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
                    <el-button type="text" @click="handleUpdate(scope.row)">上传</el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <p class="mt15"></p>
            <el-form ref="addReportRef" label-width="120px" :model="form" :rules="rules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="报告模版" prop="rtId">
                            <el-select  v-model="form.rtId"  placeholder="请选择报告模版" clearable style="width:100%">
                                <el-option v-for="option in options" :key="option.id" :value="option.id"
                                    :label="option.name" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="报告编号" prop="number" required>
                            <el-input v-model="form.number" placeholder="请输入报告编号" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="报告名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入报告名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="创建人" prop="createUser" required>
                            <el-input v-model="form.createUser" placeholder="请输入创建人" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="创建时间" prop="createTime" required>
                            <el-input v-model="form.createTime" placeholder="请输入创建时间" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save">生 成</el-button>
                    <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :title="'上传报告'" v-model="open1" width="600px" append-to-body>
            <p class="mt15"></p>
            <el-form ref="addReportRef1" label-width="100px" :model="form1" :rules="rules">
                <el-row>
                    <el-col>
                        <el-form-item label="报告文件" prop="fileId">
                            <file-upload v-model="form1.attach" :fileType="['doc', 'docx']" :limit="1"
                                @uploadFile="uploadFile" @delFile="delFile" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save1">保 存</el-button>
                    <el-button @click="open1 = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 上传进度展示 -->
        <el-dialog v-model="openCreate" title="正在生成报告" width="400px" :close-on-click-modal="false" append-to-body
            :show-close="false">
            <p></p>
            <div class="demo-progress">
                <el-progress :percentage="percentages" />
            </div>
            <div class="footer">
                <el-button plain @click="cancelUpload">取消生成</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script setup name="creatReport">
import useUserStore from '@/store/modules/user'
import useEventStore from "@/store/modules/event";
import { getModelList } from "@/api/earthEvaluaDisasterReport/reportModelManage"
import { getReportList, getReportInfo, saveReport, uploadReport } from "@/api/earthEvaluaDisasterReport/creatReport"
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const loading = ref(false);
const open = ref(false);
const open1 = ref(false);
const openCreate = ref(false);
const percentages = ref(0);
const title = ref();
const { name } = useUserStore();
const options = ref([]);
const currentEvent = computed(() => useEventStore().currentEvent);
const data = reactive({
    form: {
    },
    form1: {
    },
    rules: {
        name: [{ required: true, message: "报告名称不能为空", trigger: "blur" }],
        fileId: [{ required: true, message: "报告文件不能为空", trigger: "change" }],
        rtId: [{ required: true, message: "报告模版不能为空", trigger: "blur" }],
    }
})
const { form, rules, form1 } = toRefs(data)

// 新增
function handleCreat() {
    title.value = '报告生成';
    getReportInfo({ id: currentEvent.value.id }).then(res => {
        open.value = true;
        proxy.resetForm("addReportRef");
        form.value = {
            number: res.data,
            createUser: name,
            createTime: getNowFormatTime(),
        };
    })
}

function handleCoverReport(row){
    title.value = '报告生成';
    getReportInfo({ id: currentEvent.value.id }).then(res => {
        open.value = true;
        proxy.resetForm("addReportRef");
        form.value = {
            number: res.data,
            createUser: name,
            createTime: getNowFormatTime(),
            name:row.name,
            rtId:row.rtId,
            xsemId: row.xsemId
        };
    })
}

let cancelFunc = {}
function save() {
    proxy.$refs["addReportRef"].validate(valid => {
        if (valid) {
            if (typeof cancelFunc.c === "function") {
                cancelFunc.c('取消成功')
            }
            percentages.value = 0;
            openCreate.value = true;

            let startTime = setInterval(() => {
                if (percentages.value < 50) {
                    percentages.value += 5;
                }
                if (percentages.value == 50) {
                    clearInterval(startTime);
                    let conductTime = setInterval(() => {
                        if (percentages.value == 95) {
                            clearInterval(conductTime);
                        }
                        if (percentages.value < 96) {
                            percentages.value += 2;
                        }
                    }, 100)
                }
            }, 100)
            console.log('2222');
            saveReport({ ...form.value, xsemId: currentEvent.value.id }, cancelFunc).then(res => {
                percentages.value = 100;
                open.value = false;
                openCreate.value = false
                const { code, data, message } = res
                if (code == 200 && data != null) {
                    getList();
                    clearInterval(startTime)
                    proxy.$modal.msgSuccess('报告生成成功！')
                } else {
                    proxy.$modal.msgError(message)
                }
            }).catch(err => {
                openCreate.value = false
                if (err.message !== '取消成功') {
                    cancelFunc.c = null
                }
            })
        }
    })


}

const save1 = () => {
    proxy.$refs["addReportRef1"].validate(valid => {
        if (valid) {
            proxy.$modal.confirm('是否确认覆盖该报告？').then(function () {
                return uploadReport({ ...form1.value, xsemId: currentEvent.value.id });
            }).then(() => {
                open1.value = false;
                getList();
                proxy.$modal.msgSuccess("保存成功");
            }).catch(() => { });
        }
    })
}

// 取消生成
function cancelUpload() {
    if (typeof cancelFunc.c === "function") {
        cancelFunc.c('取消成功')
    }
    openCreate.value = false;
}

// 下载
const handleDownload = (row) => {
    var query = {
        attachId: row.fileId,
    }
    location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

// 上传
const handleUpdate = (row) => {
    open1.value = true;
    proxy.resetForm("addReportRef1");
    form1.value = {
        id: row.id,
        fileId: '',
        attach: [],
    };
}

const uploadFile = (val) => {
    form1.value.fileId = val;
    proxy.$refs['addReportRef'].validateField('fileId')
}
const delFile = () => {
    form1.value.fileId = '';
    form1.value.attach = [];
    proxy.$refs['addReportRef'].validateField('fileId')
}

/** 查询数据列表 */
function getList() {
    if (currentEvent.value) {
        loading.value = true;
        getReportList({ xsemId: currentEvent.value.id }).then(response => {
            dataList.value = response.data ? response.data : [];
            loading.value = false;
        }).catch(err => { loading.value = false });
    } else {
        dataList.value = [];
        total.value = 0;
    }
}

function getLists(){
    getModelList().then(res=>{
        options.value = res.data?res.data:[];
    })
}

//获取当前日期，格式YYYY-MM-DD
function getNowFormatDay(nowDate) {
    var char = "-";
    if (nowDate == null) {
        nowDate = new Date();
    }
    var day = nowDate.getDate();
    var month = nowDate.getMonth() + 1;//注意月份需要+1
    var year = nowDate.getFullYear();
    //补全0，并拼接
    return year + char + completeDate(month) + char + completeDate(day);
}
//获取当前时间，格式YYYY-MM-DD HH:mm:ss
function getNowFormatTime() {
    var nowDate = new Date();
    var colon = ":";
    var h = nowDate.getHours();
    var m = nowDate.getMinutes();
    var s = nowDate.getSeconds();
    //补全0，并拼接
    return getNowFormatDay(nowDate) + " " + completeDate(h) + colon + completeDate(m) + colon + completeDate(s);
}
//补全0
function completeDate(value) {
    return value < 10 ? "0" + value : value;
}

onMounted(() => {
    setTimeout(() => {
        getLists();
        getList();
    }, 200)
})
</script>
  
<style scoped lang="scss">
.title {
    margin: 0 0 20px !important;
}

.demo-progress .el-progress--line {
  margin: 40px 0;
  // margin-bottom: 15px;
  width: 350px;
}
.footer{
  text-align: center;
  padding-bottom: 20px;
}
</style>
  
  